package client.order;


import client.common.result.OrderDetailsVOResult;
import client.common.result.OrderListResult;
import client.common.result.Result;
import client.common.result.emun.ResultCodeEnum;
import client.common.vo.OrderDetailsVO;
import client.common.vo.OrderMaterialVO;
import client.common.vo.OrderVO;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import remote.service.OrderService;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * 主审核窗口，显示所有待审核的订单，并允许查看和审核订单。
 */
public class AuditOrderForm extends JFrame {
    
    private OrderTableModel tableModel;
    private JTable table;
    private JButton refreshButton;
    private JButton viewDetailsButton;
    private JComboBox<String> statusFilterComboBox;
    private JButton firstPageButton;
    private JButton previousPageButton;
    private JButton nextPageButton;
    private JButton lastPageButton;
    private JLabel pageLabel;
    private int currentPage = 1; // 当前页码
    private int totalPages = 1; // 总页数
    private OrderService orderService = new OrderService() {
    }; // 实例化 OrderService
    
    public AuditOrderForm() {
        // 设置窗口属性
        setTitle("订单审核");
        setSize(800, 500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 创建主面板
        JPanel panel = new JPanel(new BorderLayout());
        
        // 创建表格模型和表格
        tableModel = new OrderTableModel();
        table = new JTable(tableModel);
        table.setFillsViewportHeight(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setRowHeight(25);
        
        firstPageButton = new JButton("首页");
        previousPageButton = new JButton("上一页");
        nextPageButton = new JButton("下一页");
        lastPageButton = new JButton("末页");
        pageLabel = new JLabel("当前页: " + currentPage + " / " + totalPages);

// 创建分页按钮面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        paginationPanel.add(firstPageButton);
        paginationPanel.add(previousPageButton);
        paginationPanel.add(nextPageButton);
        paginationPanel.add(lastPageButton);
        paginationPanel.add(pageLabel);
        
        
        // 设置列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(100); // 订单ID
        table.getColumnModel().getColumn(1).setPreferredWidth(150); // 用户ID
        table.getColumnModel().getColumn(2).setPreferredWidth(200); // 提交时间
        table.getColumnModel().getColumn(3).setPreferredWidth(100); // 订单类型
        table.getColumnModel().getColumn(4).setPreferredWidth(100); // 状态
        
        // 添加表格到滚动面板
        JScrollPane tableScrollPane = new JScrollPane(table);
        panel.add(tableScrollPane, BorderLayout.CENTER);
        
        // 创建底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        refreshButton = new JButton("查询");
        viewDetailsButton = new JButton("查看详情");
        buttonPanel.add(refreshButton);
        buttonPanel.add(viewDetailsButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        statusFilterComboBox = new JComboBox<>(new String[]{"待审核", "已通过", "已拒绝"});
        
        // 添加主面板到窗口
        add(panel);
        
        // 添加按钮事件
        refreshButton.addActionListener(e -> loadAuditOrders());
        viewDetailsButton.addActionListener(e -> openOrderDetails());
        
        firstPageButton.addActionListener(e -> {
            currentPage = 1; // 设置为首页
            loadAuditOrders();
        });
        
        previousPageButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--; // 前往上一页
                loadAuditOrders();
            }
        });
        
        nextPageButton.addActionListener(e -> {
            if (currentPage < totalPages) {
                currentPage++; // 前往下一页
                loadAuditOrders();
            }
        });
        
        lastPageButton.addActionListener(e -> {
            currentPage = totalPages; // 设置为末页
            loadAuditOrders();
        });
        
        // 加载初始订单列表
        loadAuditOrders();
        
        buttonPanel.add(statusFilterComboBox);
        
        // 添加到底部按钮面板
        buttonPanel.add(statusFilterComboBox); // 状态选择下拉框
        buttonPanel.add(refreshButton);
        buttonPanel.add(viewDetailsButton);
        buttonPanel.add(paginationPanel); // 添加分页面板
        
        // 显示窗口
        setVisible(true);
    }
    
    /**
     * 主方法，启动应用。
     */
    public static void main(String[] args) {
        // 设置 Swing 的外观为系统默认
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new AuditOrderForm();
            }
        });
    }
    
    private String getSelectedStatus() {
        switch (statusFilterComboBox.getSelectedItem().toString()) {
            case "待审核":
                return "0";
            case "已通过":
                return "1";
            case "已拒绝":
                return "2";
            default:
                return "0"; // 处理所有状态的情况
        }
    }
    
    private void updatePaginationControls() {
        pageLabel.setText("当前页: " + currentPage + " / " + totalPages);
        firstPageButton.setEnabled(currentPage > 1);
        previousPageButton.setEnabled(currentPage > 1);
        nextPageButton.setEnabled(currentPage < totalPages);
        lastPageButton.setEnabled(currentPage < totalPages);
    }
    
    /**
     * 加载并显示待审核订单列表。
     */
    private void loadAuditOrders() {
        String status = getSelectedStatus(); // 获取选中的状态
        // 使用 SwingWorker 在后台线程中加载订单，避免阻塞 UI
        SwingWorker<OrderListResult, Void> worker = new SwingWorker<OrderListResult, Void>() {
            @Override
            protected OrderListResult doInBackground() throws Exception {
                return orderService.getOrderList(status, currentPage, 20);
            }
            
            @Override
            protected void done() {
                try {
                    OrderListResult result = get();
                    if (result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
                        // TODO 修改信息
                        //List<OrderVO> orders = result.getData();
                        Map<String, Object> resultData = result.getData();
                        List<JSONObject> jsonObjectList = (List<JSONObject>) resultData.get("data");
                        List<OrderVO> orderVOList = jsonObjectList
                                .stream()
                                .map(jsonObject -> JSON.toJavaObject(jsonObject, OrderVO.class))
                                .collect(Collectors.toList());
                        totalPages = (int) resultData.get("totalPage");
                        tableModel.setOrders(orderVOList);
                        updatePaginationControls(); // 更新分页控件状态
                    } else if (result.getCode().equals(ResultCodeEnum.NO_PERMISSION.getCode())) {
                        JOptionPane.showMessageDialog(AuditOrderForm.this, result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                        setVisible(false);
                        dispose();
                    } else {
                        JOptionPane.showMessageDialog(AuditOrderForm.this, "加载订单失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (InterruptedException | ExecutionException e) {
                    JOptionPane.showMessageDialog(AuditOrderForm.this, "加载订单异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 打开订单详情对话框。
     */
    private void openOrderDetails() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个订单进行查看。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 获取选中的订单
        OrderVO selectedOrder = tableModel.getOrderAt(selectedRow);
        if (selectedOrder == null) {
            JOptionPane.showMessageDialog(this, "未能获取选中的订单信息。", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 打开订单详情对话框
        OrderDetailsDialog dialog = new OrderDetailsDialog(this, selectedOrder);
        dialog.setVisible(true);
        
        // 根据对话框的操作刷新订单状态
        if (dialog.isAuditPerformed()) {
            // 重新加载订单列表
            loadAuditOrders();
        }
    }
    
    /**
     * 表格模型，管理订单列表的数据。
     */
    class OrderTableModel extends AbstractTableModel {
        
        private final String[] columnNames = {"订单ID", "用户ID", "提交时间", "订单类型", "状态"};
        private List<OrderVO> orders = new ArrayList<>();
        
        public void setOrders(List<OrderVO> orders) {
            this.orders = orders;
            fireTableDataChanged();
        }
        
        public OrderVO getOrderAt(int rowIndex) {
            if (rowIndex >= 0 && rowIndex < orders.size()) {
                return orders.get(rowIndex);
            }
            return null;
        }
        
        @Override
        public int getRowCount() {
            return orders.size();
        }
        
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            OrderVO order = orders.get(rowIndex);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); // 设置中文标准格式
            switch (columnIndex) {
                case 0:
                    return order.getId();
                case 1:
                    return order.getUserId();
                case 2:
                    return dateFormat.format(order.getSubmitTime()); // 格式化提交时间
                case 3:
                    return order.getInOut() == 0 ? "入库" : "出库";
                case 4:
                    return order.getStatus() == 0 ? "待审核" : (order.getStatus() == 1 ? "已通过" : "已拒绝");
                default:
                    return null;
            }
        }
        
        
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            switch (columnIndex) {
                case 0:
                case 1:
                    return Long.class;
                case 2:
                    return String.class; // 提交时间作为字符串处理
                case 3:
                case 4:
                    return String.class;
                default:
                    return Object.class;
            }
        }
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }
    }
    
    /**
     * 订单详情对话框，显示订单的详细信息并允许审核。
     */
    class OrderDetailsDialog extends JDialog {
        
        private OrderVO order;
        private boolean auditPerformed = false;
        
        private JLabel orderIdLabel;
        private JLabel userIdLabel;
        private JLabel submitTimeLabel;
        private JLabel inOutLabel;
        private JLabel statusLabel;
        private JTable materialsTable;
        private JButton approveButton;
        private JButton rejectButton;
        private JButton closeButton;
        
        private OrderDetailsTableModel detailsTableModel;
        
        public OrderDetailsDialog(JFrame parent, OrderVO order) {
            super(parent, "订单详情 - ID: " + order.getId(), true);
            this.order = order;
            
            setSize(600, 500);
            setLocationRelativeTo(parent);
            setLayout(new BorderLayout());
            
            // 上部信息面板
            JPanel infoPanel = new JPanel(new GridLayout(5, 2, 10, 10));
            infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            
            infoPanel.add(new JLabel("订单ID:"));
            orderIdLabel = new JLabel(String.valueOf(order.getId()));
            infoPanel.add(orderIdLabel);
            
            infoPanel.add(new JLabel("用户ID:"));
            userIdLabel = new JLabel(String.valueOf(order.getUserId()));
            infoPanel.add(userIdLabel);
            
            infoPanel.add(new JLabel("提交时间:"));
            submitTimeLabel = new JLabel(order.getSubmitTime().toString());
            infoPanel.add(submitTimeLabel);
            
            infoPanel.add(new JLabel("订单类型:"));
            inOutLabel = new JLabel(order.getInOut() == 0 ? "入库" : "出库");
            infoPanel.add(inOutLabel);
            
            infoPanel.add(new JLabel("状态:"));
            statusLabel = new JLabel(getStatusText(order.getStatus()));
            infoPanel.add(statusLabel);
            
            add(infoPanel, BorderLayout.NORTH);
            
            // 物料列表表格
            detailsTableModel = new OrderDetailsTableModel();
            materialsTable = new JTable(detailsTableModel);
            materialsTable.setFillsViewportHeight(true);
            JScrollPane tableScrollPane = new JScrollPane(materialsTable);
            add(tableScrollPane, BorderLayout.CENTER);
            
            // 按钮面板
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            approveButton = new JButton("通过审核");
            rejectButton = new JButton("拒绝审核");
            closeButton = new JButton("关闭");
            buttonPanel.add(approveButton);
            buttonPanel.add(rejectButton);
            buttonPanel.add(closeButton);
            add(buttonPanel, BorderLayout.SOUTH);
            
            // 按钮事件
            approveButton.addActionListener(e -> auditOrder(1));
            rejectButton.addActionListener(e -> auditOrder(2));
            closeButton.addActionListener(e -> dispose());
            
            // 根据订单状态禁用审核按钮
            if (order.getStatus() != 0) {
                approveButton.setEnabled(false);
                rejectButton.setEnabled(false);
            }
            // 加载订单详情
            loadOrderDetails();
        }
        
        /**
         * 加载订单详情信息。
         */
        private void loadOrderDetails() {
            // 使用 SwingWorker 在后台线程中加载订单详情，避免阻塞 UI
            SwingWorker<OrderDetailsVOResult, Void> worker = new SwingWorker<OrderDetailsVOResult, Void>() {
                @Override
                protected OrderDetailsVOResult doInBackground() throws Exception {
                    return orderService.getOrderDetails(order.getId());
                }
                
                @Override
                protected void done() {
                    try {
                        OrderDetailsVOResult result = get();
                        if (result.getCode() == 200) {
                            OrderDetailsVO details = result.getData();
                            populateOrderDetails(details);
                        } else {
                            JOptionPane.showMessageDialog(OrderDetailsDialog.this, "加载订单详情失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (InterruptedException | ExecutionException e) {
                        JOptionPane.showMessageDialog(OrderDetailsDialog.this, "加载订单详情异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            };
            worker.execute();
        }
        
        /**
         * 填充订单详情信息到界面。
         *
         * @param details 订单详情数据
         */
        private void populateOrderDetails(OrderDetailsVO details) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); // 设置中文标准格式
            // 更新界面信息
            submitTimeLabel.setText(dateFormat.format(details.getSubmitTime())); // 格式化提交时间
            inOutLabel.setText(details.getOrderInOut() == 0 ? "入库" : "出库");
            statusLabel.setText(getStatusText(details.getStatus()));
            
            // 更新物料列表
            detailsTableModel.setMaterials(details.getOrderMaterialVOList());
        }
        
        
        /**
         * 获取状态对应的文本描述。
         *
         * @param status 状态代码
         * @return 状态文本
         */
        private String getStatusText(Integer status) {
            if (status == null) return "未知";
            switch (status) {
                case 0:
                    return "待审核";
                case 1:
                    return "已通过";
                case 2:
                    return "已拒绝";
                default:
                    return "未知";
            }
        }
        
        /**
         * 执行订单审核操作。
         *
         * @param auditStatus 审核状态，1：通过，2：拒绝
         */
        private void auditOrder(int auditStatus) {
            // 使用 SwingWorker 在后台线程中执行审核操作
            SwingWorker<Result, Void> worker = new SwingWorker<Result, Void>() {
                @Override
                protected Result doInBackground() throws Exception {
                    return orderService.auditOrder(order.getId(), auditStatus);
                }
                
                @Override
                protected void done() {
                    try {
                        Result result = get();
                        if (result.getCode() == 200) {
                            JOptionPane.showMessageDialog(OrderDetailsDialog.this, "订单审核成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                            auditPerformed = true;
                            // 更新订单状态
                            order.setStatus(auditStatus);
                            statusLabel.setText(getStatusText(auditStatus));
                            // 禁用审核按钮
                            approveButton.setEnabled(false);
                            rejectButton.setEnabled(false);
                        } else {
                            JOptionPane.showMessageDialog(OrderDetailsDialog.this, "订单审核失败: " + result.getMessage(), "失败", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (InterruptedException | ExecutionException e) {
                        JOptionPane.showMessageDialog(OrderDetailsDialog.this, "订单审核异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            };
            worker.execute();
        }
        
        /**
         * 获取是否执行了审核操作。
         */
        public boolean isAuditPerformed() {
            return auditPerformed;
        }
        
        /**
         * 订单详情表格模型，显示订单中的物料列表。
         */
        class OrderDetailsTableModel extends AbstractTableModel {
            
            private final String[] columnNames = {"物料ID", "物料名称", "变动情况"};
            private List<OrderMaterialVO> materials = new ArrayList<>();
            
            public void setMaterials(List<OrderMaterialVO> materials) {
                this.materials = materials;
                fireTableDataChanged();
            }
            
            @Override
            public int getRowCount() {
                return materials.size();
            }
            
            @Override
            public int getColumnCount() {
                return columnNames.length;
            }
            
            @Override
            public String getColumnName(int column) {
                return columnNames[column];
            }
            
            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                OrderMaterialVO om = materials.get(rowIndex);
                switch (columnIndex) {
                    case 0:
                        return om.getMaterialId();
                    case 1:
                        return om.getMaterialName();
                    case 2:
                        return om.getVariation(); // 使用 variation 显示数量和单位的组合
                    default:
                        return null;
                }
            }
        }
    }
}